package com.zhongjian.technologycal.mall.activity.personal.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.zhongjian.technologycal.mall.R;
import com.zhongjian.technologycal.mall.alipay.AuthResult;
import com.zhongjian.technologycal.mall.alipay.PayResult;
import com.zhongjian.technologycal.mall.base.BaseActivity;
import com.zhongjian.technologycal.mall.bean.BaseBean;
import com.zhongjian.technologycal.mall.bean.MemberVIPBean;
import com.zhongjian.technologycal.mall.bean.VipPayBean;
import com.zhongjian.technologycal.mall.net.HttpRetrofitClient;
import com.zhongjian.technologycal.mall.utils.LoadingDialog;
import com.zhongjian.technologycal.mall.utils.NetWorkUtils;
import com.zhongjian.technologycal.mall.utils.ToastUitl;
import com.zhongjian.technologycal.mall.utils.UserUtils;
import com.zhongjian.technologycal.mall.view.PasswordInputView;

import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import rx.Subscriber;

/**
 * Created by wei on 2017/12/14.
 * 会员升级页面实现
 */

public class VipLevelActivity extends BaseActivity {
    @BindView(R.id.tv_main_title)
    TextView tv_main_title;
    @BindView(R.id.ll_vip)
    LinearLayout ll_vip;
    private int REQUEST_READ_PHONE_STATE = 1001;
    @BindView(R.id.ll_blue_pay)
    LinearLayout ll_blue_pay;
    @BindView(R.id.commit_tv_level)
    TextView commit_tv_level;
    @BindView(R.id.level_tv_month)
    TextView level_tv_month;
    @BindView(R.id.level_tv_money)
    TextView level_tv_money;
    private int type;
    private int onClickType = 0;
    private Dialog picChooseDialog = null;
    private int state = 0;
    private Dialog payDialog = null;
    private String orderNo;
    private String userName;

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult(msg.obj.toString());
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        ToastUitl.showShort("支付成功");
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        ToastUitl.showShort("支付取消");
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        Toast.makeText(VipLevelActivity.this,
                                "授权成功\n" + String.format("authCode:%s", authResult.getAuthCode()), Toast.LENGTH_SHORT)
                                .show();
                        ToastUitl.showShort("授权成功");
                    } else {
                        // 其他状态值则为授权失败
                        ToastUitl.showShort("授权失败");

                    }
                    break;
                }
                default:
                    break;
            }
        }
    };


    @Override
    protected void beforeInit() {
        super.beforeInit();
//        StatusBarUtil.setColorNoTranslucent(this, getResources().getColor(R.color.border_color));
//        StatusBarUtil.setMiuiStatusBarDarkMode(this, true);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        tv_main_title.setText("我要升级");
        userName = getIntent().getStringExtra("userName");
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_vip_level;
    }

    @OnClick(R.id.iv_back_page)
    public void onClickBack() {
        finish();
    }

    @Override
    public void initPresenter() {
        initViewRequestHttp();

    }

    /**
     * 弹出对话框
     */
    private void initshowDialog(Context context) {
        state = 0;
        picChooseDialog = new Dialog(context, R.style.pic_choose_dialog_progress);
        View view = LayoutInflater.from(context).inflate(
                R.layout.info_choose_paystyle_dialog, null);
        final TextView lev_tv_dialog_commit = view.findViewById(R.id.lev_tv_dialog_commit);
        final LinearLayout lev_ll_dialog_alipay = view.findViewById(R.id.lev_ll_dialog_alipay);
        final LinearLayout lev_ll_dialog_credit = view.findViewById(R.id.lev_ll_dialog_credit);
        final ImageView lev_iv_dialog_choice0 = view.findViewById(R.id.lev_iv_dialog_choice0);
        final ImageView lev_iv_dialog_choice1 = view.findViewById(R.id.lev_iv_dialog_choice1);

        lev_ll_dialog_alipay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                lev_iv_dialog_choice0.setImageResource(R.mipmap.chose);
                lev_iv_dialog_choice1.setImageResource(R.mipmap.not_chose);
                state = 1;
            }
        });
        lev_ll_dialog_credit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                lev_iv_dialog_choice0.setImageResource(R.mipmap.not_chose);
                lev_iv_dialog_choice1.setImageResource(R.mipmap.chose);
                state = 2;
            }
        });
        lev_tv_dialog_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (onClickType == 0) {
                    if (state == 0) {
                        ToastUitl.showShort("请选择支付方式～");
                    } else if (state == 1) {
                        initViewBluePay(1);
                        picChooseDialog.dismiss();
                    } else if (state == 2) {
                        initViewBluePay(0);
                        picChooseDialog.dismiss();
                    }
                } else if (onClickType == 1) {
                    if (state == 0) {
                        ToastUitl.showShort("请选择支付方式～");
                    } else if (state == 1) {
                        initViewRequest(1);
                        picChooseDialog.dismiss();
                    } else if (state == 2) {
                        initViewRequest(0);
                        picChooseDialog.dismiss();
                    }

                }

            }
        });
        Window window = picChooseDialog.getWindow();
        window.setContentView(view);
        window.setGravity(Gravity.BOTTOM);
        window.setLayout(android.view.WindowManager.LayoutParams.MATCH_PARENT,
                android.view.WindowManager.LayoutParams.WRAP_CONTENT);
        window.setWindowAnimations(R.style.popupWindowAnimation);
        picChooseDialog.setCanceledOnTouchOutside(true);
        picChooseDialog.show();
    }

    /**
     * 99元绿色通道
     */
    @OnClick(R.id.ll_blue_pay)
    public void onClickPay() {
        onClickType = 0;
        initshowDialog(this);
    }

    /**
     * 升级VIP
     */
    @OnClick(R.id.ll_vip)
    public void onClickLevel() {
        onClickType = 1;
        initshowDialog(this);
    }

    /**
     * 直接升级
     */
    @OnClick(R.id.commit_tv_level)
    public void onClickNickname() {
        initViewDirectUpdate();
    }

    /**
     * 升级VIP
     */
    private void initViewRequest(int type) {
        if (!NetWorkUtils.isNetConnected(getBaseContext())) {
            ToastUitl.showShort(R.string.no_net);
            return;
        }
        HttpRetrofitClient.getInstance(getBaseContext()).postUrlRequestLevel(
                UserUtils.getUserToken(), type, 1,
                new Subscriber<ResponseBody>() {
                    @Override
                    public void onStart() {
                        super.onStart();
                        LoadingDialog.showDialogForLoading(VipLevelActivity.this);
                    }

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        LoadingDialog.cancelDialogForLoading();
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        LoadingDialog.cancelDialogForLoading();
                        try {
                            Gson gson = new Gson();
                            VipPayBean vipPayBean = gson.fromJson(responseBody.string(), VipPayBean.class);
                            if (vipPayBean.getError_code() == 0) {
                                if (state == 1) {
                                    final String payInfo = vipPayBean.getData();
                                    Runnable payRunnable = new Runnable() {
                                        @Override
                                        public void run() {
                                            // 构造PayTask 对象
                                            PayTask alipay = new PayTask(
                                                    VipLevelActivity.this);
                                            // 调用支付接口，获取支付结果
                                            String result = alipay.pay(payInfo, true);
                                            Message msg = new Message();
                                            msg.what = SDK_PAY_FLAG;
                                            msg.obj = result;
                                            mHandler.sendMessage(msg);
                                        }
                                    };
                                    // 必须异步调用
                                    Thread payThread = new Thread(payRunnable);
                                    payThread.start();
                                } else if (state == 2) {
                                    orderNo = vipPayBean.getData();
                                    payDialog = new Dialog(VipLevelActivity.this, R.style.dialog_style1);
                                    LinearLayout layout;
                                    LayoutInflater inflater = (LayoutInflater) VipLevelActivity.this
                                            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                                    layout = (LinearLayout) inflater.inflate(R.layout.dialog_hint,
                                            null);
                                    final PasswordInputView tv_hint = (PasswordInputView) layout
                                            .findViewById(R.id.again_paypswd_pet);
                                    layout.findViewById(R.id.dialog_btn_cancel).setOnClickListener(
                                            new View.OnClickListener() {

                                                @Override
                                                public void onClick(View v) {
                                                    payDialog.dismiss();
                                                }
                                            });
                                    layout.findViewById(R.id.dialog_btn_ensure).setOnClickListener(
                                            new View.OnClickListener() {
                                                @Override
                                                public void onClick(View view) {
                                                    if (TextUtils.isEmpty(tv_hint.getText().toString().trim())) {
                                                        ToastUitl.showShort("支付密码不能为空");
                                                        return;
                                                    } else if (tv_hint.getText().toString().trim().length() < 6) {
                                                        ToastUitl.showShort("请输入6位的支付密码");
                                                        return;
                                                    }
                                                    initRequestPayPassword(tv_hint.getText().toString().trim());

                                                }
                                            });
                                    payDialog.setContentView(layout);
                                    payDialog.show();
                                }

                            } else if (vipPayBean.getError_code() == 1) {
                                ToastUitl.showShort(vipPayBean.getError_message());

                            } else if (vipPayBean.getError_code() == 2) {
                                ToastUitl.showShort(vipPayBean.getError_message());
                            } else if (vipPayBean.getError_code() == 3) {
                                Intent intent = new Intent();
                                intent.setAction("com.broadcast.info_out_line");
                                sendBroadcast(intent);
                            } else if (vipPayBean.getError_code() == -1) {
                                ToastUitl.showShort(vipPayBean.getError_message());
                            }


                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                });

    }

    /**
     * 99元绿色通道
     */
    private void initViewBluePay(int type) {
        if (!NetWorkUtils.isNetConnected(getBaseContext())) {
            ToastUitl.showShort(R.string.no_net);
            return;
        }
        HttpRetrofitClient.getInstance(getBaseContext()).postUrlRequestLevel(
                UserUtils.getUserToken(), type, 0,
                new Subscriber<ResponseBody>() {
                    @Override
                    public void onStart() {
                        super.onStart();
                        LoadingDialog.showDialogForLoading(VipLevelActivity.this);
                    }

                    @Override
                    public void onCompleted() {
                        LoadingDialog.cancelDialogForLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                        LoadingDialog.cancelDialogForLoading();
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        LoadingDialog.cancelDialogForLoading();
                        try {
                            Gson gson = new Gson();
                            VipPayBean vipPayBean = gson.fromJson(responseBody.string(), VipPayBean.class);
                            if (vipPayBean.getError_code() == 0) {
                                if (state == 1) {
                                    final String payInfo = vipPayBean.getData();
                                    Runnable payRunnable = new Runnable() {
                                        @Override
                                        public void run() {
                                            // 构造PayTask 对象
                                            PayTask alipay = new PayTask(
                                                    VipLevelActivity.this);
                                            // 调用支付接口，获取支付结果
                                            String result = alipay.pay(payInfo, true);
                                            Message msg = new Message();
                                            msg.what = SDK_PAY_FLAG;
                                            msg.obj = result;
                                            mHandler.sendMessage(msg);
                                        }
                                    };
                                    // 必须异步调用
                                    Thread payThread = new Thread(payRunnable);
                                    payThread.start();
                                } else if (state == 2) {
                                    orderNo = vipPayBean.getData();
                                    payDialog = new Dialog(VipLevelActivity.this, R.style.dialog_style1);
                                    LinearLayout layout;
                                    LayoutInflater inflater = (LayoutInflater) VipLevelActivity.this
                                            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                                    layout = (LinearLayout) inflater.inflate(R.layout.dialog_hint,
                                            null);
                                    final PasswordInputView tv_hint = (PasswordInputView) layout
                                            .findViewById(R.id.again_paypswd_pet);
                                    layout.findViewById(R.id.dialog_btn_cancel).setOnClickListener(
                                            new View.OnClickListener() {

                                                @Override
                                                public void onClick(View v) {
                                                    payDialog.dismiss();
                                                }
                                            });
                                    layout.findViewById(R.id.dialog_btn_ensure).setOnClickListener(
                                            new View.OnClickListener() {
                                                @Override
                                                public void onClick(View view) {
                                                    if (TextUtils.isEmpty(tv_hint.getText().toString().trim())) {
                                                        ToastUitl.showShort("支付密码不能为空");
                                                        return;
                                                    } else if (tv_hint.getText().toString().trim().length() < 6) {
                                                        ToastUitl.showShort("请输入6位的支付密码");
                                                        return;
                                                    }
                                                    initRequestPayPassword(tv_hint.getText().toString().trim());

                                                }
                                            });
                                    payDialog.setContentView(layout);
                                    payDialog.show();
                                }

                            } else if (vipPayBean.getError_code() == 1) {
                                ToastUitl.showShort(vipPayBean.getError_message());

                            } else if (vipPayBean.getError_code() == 2) {
                                ToastUitl.showShort(vipPayBean.getError_message());
                            } else if (vipPayBean.getError_code() == 3) {
                                Intent intent = new Intent();
                                intent.setAction("com.broadcast.info_out_line");
                                sendBroadcast(intent);
                            } else if (vipPayBean.getError_code() == -1) {
                                ToastUitl.showShort(vipPayBean.getError_message());
                            }else{
                                ToastUitl.showShort(vipPayBean.getError_message());
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                });

    }


    /**
     * 初始化数据
     */
    private void initViewRequestHttp() {
        if (!NetWorkUtils.isNetConnected(getBaseContext())) {
            ToastUitl.showShort(R.string.no_net);
            return;
        }
        HttpRetrofitClient.getInstance(getBaseContext())
                .getUrlRequestEntrance(UserUtils.getUserToken(), new Subscriber<ResponseBody>() {

                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        try {
                            Gson gson = new Gson();
                            MemberVIPBean memberVIPBean = gson.fromJson(responseBody.string(), MemberVIPBean.class);
                            if (memberVIPBean.getError_code() == 0) {
                                if (memberVIPBean.getData().getGC().getIsExit() == 1) {
                                    ll_blue_pay.setVisibility(View.VISIBLE);
                                    level_tv_month.setText("" + "（" + memberVIPBean.getData().getGC().getGcNeedPay() + "元)");
                                } else if (memberVIPBean.getData().getGC().getIsExit() == 0) {
                                    ll_blue_pay.setVisibility(View.VISIBLE);
                                    ll_blue_pay.setClickable(false);
                                }
                                if (memberVIPBean.getData().getVIP().getIsExit() == 1) {
                                    ll_vip.setVisibility(View.VISIBLE);
                                    level_tv_money.setText("累计分值到（" + memberVIPBean.getData().getVIP().getNeedPay() + ")");

                                } else if (memberVIPBean.getData().getVIP().getIsExit() == 0) {
                                    ll_vip.setVisibility(View.VISIBLE);
                                    ll_vip.setClickable(false);
                                }
                                if (memberVIPBean.getData().getDirectUpdate().getIsExit() == 0) {
                                    commit_tv_level.setVisibility(View.VISIBLE);
                                    commit_tv_level.setClickable(false);
                                } else if (memberVIPBean.getData().getDirectUpdate().getIsExit() == 1) {
                                    commit_tv_level.setVisibility(View.VISIBLE);
                                }
                                if (memberVIPBean.getData().getDirectUpdate().getType() == 1) {
                                    commit_tv_level.setText("直接升级VIP");
                                    type = memberVIPBean.getData().getDirectUpdate().getType();
                                } else if (memberVIPBean.getData().getDirectUpdate().getType() == 2) {
                                    commit_tv_level.setText("直接升级准代");
                                    type = memberVIPBean.getData().getDirectUpdate().getType();
                                } else if (memberVIPBean.getData().getDirectUpdate().getType() == 3) {
                                    commit_tv_level.setText("直接升级代理");
                                    type = memberVIPBean.getData().getDirectUpdate().getType();
                                }

                            } else if (memberVIPBean.getError_code() == 1) {


                            } else if (memberVIPBean.getError_code() == 3) {
                                Intent intent = new Intent();
                                intent.setAction("com.broadcast.info_out_line");
                                sendBroadcast(intent);
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                });

    }

    /**
     * 直接升级
     */
    private void initViewDirectUpdate() {
        if (!NetWorkUtils.isNetConnected(getBaseContext())) {
            ToastUitl.showShort(R.string.no_net);
            return;
        }
        HttpRetrofitClient.getInstance(getBaseContext())
                .postUrlRequestUpdate(UserUtils.getUserToken(), type, new Subscriber<ResponseBody>() {
                    @Override
                    public void onStart() {
                        super.onStart();
                        LoadingDialog.showDialogForLoading(VipLevelActivity.this);
                    }

                    @Override
                    public void onCompleted() {
                     LoadingDialog.cancelDialogForLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                     Log.v("onError",e.getMessage());
                     LoadingDialog.cancelDialogForLoading();
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        LoadingDialog.cancelDialogForLoading();
                        try {
                            Gson gson = new Gson();
                            BaseBean baseBean = gson.fromJson(responseBody.string(), BaseBean.class);
                            if (baseBean.getError_code() == 0) {
                                ToastUitl.showShort(baseBean.getError_message());
                                finish();
                            } else if (baseBean.getError_code() == 3) {
                                Intent intent = new Intent();
                                intent.setAction("com.broadcast.info_out_line");
                                sendBroadcast(intent);
                            } else {
                                ToastUitl.showShort(baseBean.getError_message());
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }


                    }
                });


    }

    /**
     * 验证支付密码
     * @param password
     */
    private void initRequestPayPassword(String password) {
        if (!NetWorkUtils.isNetConnected(getBaseContext())) {
            ToastUitl.showShort(R.string.no_net);
            return;
        }
        HttpRetrofitClient.getInstance(getBaseContext())
                .postUrlRequestPayPassword(UserUtils.getUserToken(),
                        password, new Subscriber<ResponseBody>() {
                            @Override
                            public void onStart() {
                                super.onStart();
                                LoadingDialog.showDialogForLoading(VipLevelActivity.this);
                            }

                            @Override
                            public void onCompleted() {
                                LoadingDialog.cancelDialogForLoading();

                            }

                            @Override
                            public void onError(Throwable e) {
                                Log.v("onError",e.getMessage());
                                LoadingDialog.cancelDialogForLoading();
                            }

                            @Override
                            public void onNext(ResponseBody responseBody) {
                                LoadingDialog.cancelDialogForLoading();
                                try {
                                    Gson gson = new Gson();
                                    BaseBean baseBean = gson.fromJson(responseBody.string(), BaseBean.class);
                                    if (baseBean.getError_code() == 0) {
                                        initViewHandleVipOrder(orderNo);
                                        payDialog.dismiss();
                                    } else if (baseBean.getError_code() == -1) {
                                        Intent intent = new Intent();
                                        intent.setClass(getBaseContext(), SettingPayPasswordActivity.class);
                                        intent.putExtra("username", userName);
                                        startActivity(intent);
                                        ToastUitl.showShort(baseBean.getError_message());
                                        payDialog.dismiss();
                                        /**
                                         * 冻结
                                         */
                                    } else if (baseBean.getError_code() == 5) {
                                        ToastUitl.showShort(baseBean.getError_message());
                                        payDialog.dismiss();
                                        /**
                                         * 密码错误
                                         */
                                    } else if (baseBean.getError_code() == 1) {
                                        ToastUitl.showShort(baseBean.getError_message());
                                    } else if (baseBean.getError_code() == 3) {
                                        Intent intent = new Intent();
                                        intent.setAction("com.broadcast.info_out_line");
                                        sendBroadcast(intent);
                                    } else {
                                        ToastUitl.showShort(baseBean.getError_message());
                                    }

                                } catch (Exception e) {
                                    e.printStackTrace();
                                }


                            }
                        });

    }
    /**
     *
     * @param orderNo
     * 处理现金支付
     */
    private void initViewHandleVipOrder(String orderNo) {
        if (!NetWorkUtils.isNetConnected(getBaseContext())) {
            ToastUitl.showShort(R.string.no_net);
            return;
        }
        HttpRetrofitClient.getInstance(getBaseContext()).postUrlRequestsyncHandleVipOrder(UserUtils.getUserToken(), orderNo,
                new Subscriber<ResponseBody>() {
                    @Override
                    public void onStart() {
                        super.onStart();
                        LoadingDialog.showDialogForLoading(VipLevelActivity.this);
                    }

                    @Override
                    public void onCompleted() {
                        LoadingDialog.cancelDialogForLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.v("onError",e.getMessage());
                        LoadingDialog.cancelDialogForLoading();
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        LoadingDialog.cancelDialogForLoading();
                        try {
                            Gson gson = new Gson();
                            BaseBean baseBean = gson.fromJson(responseBody.string(),BaseBean.class);
                            if(baseBean.getError_code() == 0){
                                ToastUitl.showShort(baseBean.getError_message());
                                finish();
                            }else if(baseBean.getError_code() == 3){
                                Intent intent = new Intent();
                                intent.setAction("com.broadcast.info_out_line");
                                sendBroadcast(intent);
                            }else{
                                ToastUitl.showShort(baseBean.getError_message());
                            }
                        }catch (Exception e){
                            e.printStackTrace();
                        }

                    }
                });

    }


}
